const puppeteer = require('puppeteer-core')
const config = require('./conf')
const constrants = require('./constraints')
const { getThreads } = require('./scripts')
const nconf = require('nconf')
const { sendMail } = require('./mail')

let browser
let wsEndpoint

nconf.file('./config.json')

async function login() {
    if(!browser) {
        browser = await createBrowser()
    }
    
    let page = await browser.newPage()
    await page.goto(constrants.thread.index)
}

async function start() {
    if(!browser) {
        browser = await createBrowser()
    }

    let page = await browser.newPage()
    await page.goto(constrants.thread.rjdz)
    

    // await page.addScriptTag({
    //     path: './node_modules/axios/dist/axios.js'
    // })

    let threads = []
    let times = 0

    let updateInt = setInterval(async () => {
        page.reload()
        let newThreads = await getUnreadInOnePage(page)
        console.log(...newThreads)
        threads.push(...newThreads)
        threads.sort((a, b) => {
            // return a.id * 1 < b.id * 1 ? -1 : 1 // 正序排
            return a.id * 1 > b.id * 1 ? -1 : 1 // 倒序排
        })

        times++

        if (threads.length >= 15) {
            send(threads)
            threads = []
            times = 0
        } else if (times >= 30) {
            send(threads)
            threads = []
            times = 0
        }
    }, 1000 * 60)

}

async function send(threads) {
    let html = ''

    for(let idx = 0; idx < threads.length; idx++) {
        let t = threads[idx]
        html += `<hr>
                 <p>${t.url}</p><hr>
                 <p>${t.overview}</p><hr>
                 <p>${t.content}</p><hr>`
    }

    sendMail({
        to: '553308706@qq.com',
        subject: `${threads.length} posts updated`,
        html
    })
}

async function getUnreadInOnePage(page) {
    await page.waitForSelector('#newspecial')
    await page.waitForSelector('tbody#separatorline')

    let threads = await page.$eval('tbody#separatorline', 
        getThreads, constrants.thread.index)
    
    let newThreads = []

    let tpage = await browser.newPage()
    for(let idx = 0; idx < threads.length; idx++) {
        let t = threads[idx]
        if(t.id > nconf.get('newestThread')) {
            // document.querySelector('div.pcb').outerText
            let nt = {}
            nt.url = t.url
            nt.id = t.id
            nt.overview = t.overview
            await tpage.goto(t.url)
            // let content = 
            await tpage.$eval('div.pcb', div => div.outerText)
                .then(content => {
                    nt.content = content
                })
                .catch(err => {})
            // t.content = content

            newThreads.push(nt)
        } else {
            break
        }
    }
    
    await tpage.close()
    
    nconf.set('newestThread', threads[0].id)
    nconf.save()
    
    return newThreads
}

async function createBrowser() {
    if (wsEndpoint) {
        return puppeteer.connect({
            browserWSEndpoint: wsEndpoint
        })
    } else {
        const b = await puppeteer.launch({
            executablePath: config.browser.executePath,
            headless: config.browser.headless,
            defaultViewport: {
                width: 1478,
                height: 759
            },
            userDataDir: config.browser.userDataDir
        })
        wsEndpoint = b.wsEndpoint()
        console.log(wsEndpoint)
        return b
    }
}

module.exports = {
    login,
    start
}
